<?php
class ModulesModel extends Model {
	private $newsDB;
	private $productDB;
	private $categoryDB;
	private $product_categoryDB;
	public function __construct(){
		parent::__construct();
		$this->newsDB = D('News');
		$this->productDB = D('Product');
		$this->product_categoryDB = D('Product_category');
		$this->categoryDB = D('Category');
	}
	
	protected $_validate = array(
	    array('title','require','请填写标题！'), 
    );
	protected $_auto = array(
        array('datetime','time',1,'function'),
		array('datetime','time',2,'function'),
    );
	public function getListToArray($map,$view = '', $Cache=true, $ajax = IS_AJAX){ 
		$re=$this->where($map)->order('sort,id')->select();
		
		if($re!==false){
			unset($map['id']);
			unset($map['pages_id']);
			foreach($re as $k=>$v){
				$v['style'] = deleteScript($v['style']);
			    $v['content'] = deleteScript($v['content']);
				$arr = explode('.',$v['dataname']);
				if($view != '' && trim($arr[0]) !=''){
					if(is_array($view)){
					    $re[$k]['dataname'] = parseTemplateData($v['dataname'], $view[$arr[0]]);
					}else{
						$re[$k]['dataname'] = parseTemplateData($v['dataname'], $view -> get($arr[0]));
					}
				}
				
				$diydata = unserialize($this -> where(array('id' => $v['id'])) -> getField('diydata'));
				foreach($diydata as $key => $value){
					$re[$k]['diysource'] = str_replace('{'.$key.'}', replacebr($value), $re[$k]['diysource']);
					
					if(strpos($key, '_link') > 0){
						if($value != ''){
							$re[$k]['diysource'] = str_replace('<'.$key.'>', '<a href="'.replacelink($value).'">', $re[$k]['diysource']);
							$re[$k]['diysource'] = str_replace('</'.$key.'>', '</a>', $re[$k]['diysource']);
						}else{
							$re[$k]['diysource'] = str_replace('<'.$key.'>', '', $re[$k]['diysource']);
							$re[$k]['diysource'] = str_replace('</'.$key.'>', '', $re[$k]['diysource']);
						}
					}
				}
				if($re[$k]['diysource'] != ''){
					$re[$k]['diysource'] .= '<div style="display:none;"></div>';
					$view -> assign('v', $v); 
					$re[$k]['content'] = $view -> fetch('',$re[$k]['diysource']);
				}
				
				if($v['import'] > 0){
					$re[$k]['content'] = $this->getListToString($v['import'], $view, $Cache, $ajax);
					
				}
				//万能表单
				if($v['type'] == 16){
					$re[$k]['content'] = D('Form') -> where(array('id' => $v['form_id'])) ->createForm($view);
				}
				$map['pid'] = $v['id'];
				$re[$k]['sub']=$this->getListToArray($map, $view, $Cache, $ajax);
			}
			return $re;
		}
	}
	
	
	//获取一个模块代码
	public function getModulesSource($id, $view){
		$modules = $this -> getListToArray(array('id'=> $id),$view);
		$view->assign('v',$modules[0]);
		$htmlfile = TMPL_PATH.'Home/TemplateDefault/Modules-'.$modules[0]['filename'].C('TMPL_TEMPLATE_SUFFIX');
		$cssfile = TMPL_PATH.'Home/TemplateDefault/Css/Modules-'.$modules[0]['filename'].C('TMPL_TEMPLATE_SUFFIX');
		
		
		
		$content = $view->fetch($htmlfile);
		if(!isset($_GET['ajaxlist'])){
			$style = '<style>'.$view->fetch($cssfile).'</style>';
		}else{
			$style = '';
		}
		
		return $style.$content;
	}
	
	
	
	
	//根据页面ID返回渲染结果
	public function getListToString($pages_id, $view, $Cache=true, $ajax = IS_AJAX){
		
		$pageDb = M('Pages');
		if(defined('__PAGERELATEID__') && $pages_id > 0){
			$relatepage = $pageDb->where(array('site_id' => __PAGERELATEID__, 'relate_id' => $pages_id))->find();
			if($relatepage){
				$pages_id = $relatepage['id'];
			}
		}
		
		if(isset($_GET['vajax'])){
			$ajax = true;
		}
		if(!$ajax && !is_spider()){
			return '';
		}
		//判断页面是否存在，防止资源消耗
		if(!$pages_id){
			return '';
		}
		
		//查找到页面
		
		$page = $pageDb-> where(array('id' => $pages_id)) -> find();
		if(!$page){
			return '页面不存在！该页面可能已经被管理员删除！';
		}
		
		$string = array();
		
		$s = F(md5(__SELF__.$pages_id));
		if($s && $Cache){
			return $s;
		}
		
		$modulesList = $this->getListToArray(array('pages_id' => $pages_id, 'pid' => 0), $view, $Cache, $ajax);
		foreach($modulesList as $k => $v){
			$view->assign('v',$v);
			$string['modules_'.$k] = $view->fetch(TMPL_PATH.'Home/TemplateDefault/Modules-'.$v['filename'].C('TMPL_TEMPLATE_SUFFIX'));
		}
		//if(__SITEID__ == 13){dump($string);}
		$view->assign($string);
		if($page['source'] == ''){
			return '页面已经损坏！';
		}
		//渲染
		F(md5(__SELF__.$pages_id),$this->getListToStyle($pages_id,$view).setDataOriginal($view -> fetch('',$page['source'])));
		return F(md5(__SELF__.$pages_id));
	}
	 
	//根据页面ID返回渲染样式结果
	public function getListToStyle($pages_id, $view){
		
		
		if(isset($_GET['ajaxlist'])){
			return '';
		}
		
		$style = F('pages_'.$pages_id);
		if($style){
			return $style;
		}
		
		$string = array();
		$modulesList = $this->getListToArray(array('pages_id' => $pages_id, 'pid' => 0), $view);
		//F('123', $modulesList);
		foreach($modulesList as $k => $v){
			$view->assign('v',$v);
			$string['modules_'.$k] = $view->fetch(TMPL_PATH.'Home/TemplateDefault/Css/Modules-'.$v['filename'].C('TMPL_TEMPLATE_SUFFIX'));
			
			
		}
		
		F('pages_'.$pages_id, '<style>'.implode('',$string).'</style>');
		return '<style>'.implode('',$string).'</style>';
	}
	
	
	
	//复制站点模块
	public function copy($siteid, $tositeid,$map, $pid = 0, $pages_id = 0){
		$re=$this->where($map)->order('sort,id')->select();
		if($re!==false){
			foreach($re as $k=>$v){
				//记录导航项的模块ID，便于复制导航
				$navModules_id = $v['id'];
				$map['pid'] = $v['id'];
				$v['site_id'] = $tositeid;
				$v['pages_id'] = $pages_id;
				unset($v['id']);
				
				if($v['import'] > 0){
					$v['import'] = D('Pages') -> copyimport($siteid, $tositeid, $v['import']);
				}
				if($v['form_id'] > 0){
					D('Form') -> copy($siteid, $tositeid, array('id' => $v['form_id']));
					$v['form_id'] = (int)D('Form') -> where(array('rid' => $v['form_id'])) -> getField('id');
				}
				$v['pid'] = $pid;
				$pid1 = $this->data($v)->add();
				echo '<script>window.parent.progress("写入一个模块");</script>';
				ob_flush();
                flush();
				//复制导航项
				D('Nav') -> copy($siteid, $tositeid, array('modules_id' => $navModules_id, 'pid' => 0), 0, $pid1);
				
				
				$this->copy($siteid, $tositeid,$map, $pid1, $pages_id);
			}
			return true;
		}
	}
	
	//复制站点模块
	public function copyself($siteid, $tositeid,$map, $pid = 0,$pages_id = 0, $ids = array(),$returnid = 0){
		if(!empty($ids)){
		    $map['id'] = array('not in', $ids);
		}
		$re=$this->where($map)->order('sort,id')->select();
		//print_r($map);
		if(is_array($re)){
			foreach($re as $k=>$v){
				$map['pid'] = $v['id'];
				$navModules_id = $v['id'];
				$v['site_id'] = $tositeid;
				$v['pages_id'] = $pages_id;
				unset($v['id']);
				$v['pid'] = $pid;
				$ret = $pid1 = $this->data($v)->add();
				//复制导航项
				D('Nav') -> copyself($siteid, $tositeid, array('modules_id' => $navModules_id, 'pid' => 0), 0, $pid1);
				if($returnid == 0){
					$returnid = $ret;
				}
				$ids[] = $pid1;
				$this->copyself($siteid, $tositeid,$map, $pid1, $pages_id, $ids, $returnid);
			}
			return $returnid;
		}
	}
	
	
	
	
	
	public function getListToArray1($pid=0,$deep=0,$arr=array()){
		$re=$this->where(array('pid'=>$pid))->order('sort')->select();
		if($re!==false){
			$deep++;
			foreach($re as $k=>$v){
				$v['deep']=$deep;
				$arr[]=$v;
				$arr=$this->getListToArray1($v['id'],$deep,$arr);
			}
			return $arr;
		}
	}
	
	private function getTemplate_id($siteid){
		$ret = M('Site')->where(array('id' => $siteid)) -> find();
		return $ret['template_id'];
	}
	
	
	public function getModulesList($siteid,$filename,$view = ''){
		$template_id = $this->getTemplate_id($siteid);
		$data = $this->getListToArray(array('template_id'=> $template_id,'site_id' => $siteid, 'templatefilename' => $filename,'pid' => 0),$view);
		return $data; 
	}
	//删除模块包含子级
	function deleteAll($id = 0){
		$this->where(array('id' => $id))->delete();
		$list = $this->where(array('pid' => $id))->select();
		foreach($list as $k => $v){
			$this->deleteAll($v['id']);
		}
	}
	
	
	
	//复制完站点后刷新数据
	public function _flush($site_id = 0){
		
		$modules_list = $this -> where(array('site_id' => $site_id)) -> select();
		//更新该模块中的数据
		foreach($modules_list as $k => $v){
			$list = unserialize($v['content']);
			$contentArray = array();
			foreach($list as $key => $val){
				//1、Product_category；2、Product；3、Category；4、News
				if($val['table_name'] == 4){ 
					$contentArray[] = $this -> newsDB -> where(array('relate_id' => $val['id'], 'site_id' => $site_id)) -> Field(array_keys($val)) -> find();
				}
				elseif($val['table_name'] == 2){
					$contentArray[] = $this -> productDB -> where(array('relate_id' => $val['id'], 'site_id' => $site_id)) -> Field(array_keys($val)) -> find();
				}
				elseif($val['table_name'] == 1){
					$contentArray[] = $this -> product_categoryDB -> where(array('relate_id' => $val['id'], 'site_id' => $site_id)) -> Field(array_keys($val)) -> find();
				}
				elseif($val['table_name'] == 3){
					$contentArray[] = $this -> categoryDB -> where(array('relate_id' => $val['id'], 'site_id' => $site_id)) -> Field(array_keys($val)) -> find();
				}
			}
			
			
			if(!empty($contentArray)){
				$v['content'] = serialize($contentArray);
				
				$this -> where(array('id' => $v['id'], 'site_id' => $site_id)) -> data(array('content' => $v['content'])) -> save();
				
			}
		}
	}
}
